<template>
  <div class="collection-practice-page">
    <!-- 顶部导航栏 -->
    <el-header class="navbar">
      <div class="logo">思不罔学习平台</div>
      <el-menu mode="horizontal" :default-active="activeMenu" @select="handleSelect">
        <el-menu-item index="1" @click="goBackHome">首页</el-menu-item>
        <el-menu-item index="2" @click="goToPersonal">个人中心</el-menu-item>
        <el-menu-item index="3" @click="goToCollection">我的收藏</el-menu-item>
      </el-menu>
      <div class="auth-buttons">
        <el-button link @click="goToLogin">退出登录</el-button>
      </div>
    </el-header>

    <!-- 主体内容 -->
    <el-main class="practice-content">
      <div class="collection-header">
        <div class="header-left">
          <i class="fas fa-bookmark"></i>
          <h1>我的收藏题目</h1>
        </div>
        <el-button type="primary" @click="startPractice" class="practice-btn">
          <i class="fas fa-play"></i> 做收藏题
        </el-button>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-icon collection">
            <i class="fas fa-bookmark"></i>
          </div>
          <div class="stat-content">
            <h3>收藏题目</h3>
            <div class="value">{{ stats.total }}</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon collection">
            <i class="fas fa-bookmark"></i>
          </div>
          <div class="stat-content">
            <h3>包含专业</h3>
            <div class="value">{{ stats.majors }}</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon category">
            <i class="fas fa-folder"></i>
          </div>
          <div class="stat-content">
            <h3>分类数量</h3>
            <div class="value">{{ stats.categories }}</div>
          </div>
        </div>
      </div>

      <!-- 筛选区域 -->
      <div class="filters">
        <div class="filter-group">
          <h3>专业分类</h3>
          <el-select
              v-model="filterMajor"
              placeholder="选择专业"
              size="large"
              style="width: 100%"
              clearable
          >
            <el-option label="全部专业" value="all"></el-option>
            <el-option
                v-for="major in majorOptions"
                :key="major.value"
                :label="major.label"
                :value="major.value"
            ></el-option>
          </el-select>
        </div>

        <div class="filter-group">
          <h3>题目难度</h3>
          <el-select
              v-model="filterDifficulty"
              placeholder="选择难度"
              size="large"
              style="width: 100%"
              clearable
          >
            <el-option label="全部难度" value="all"></el-option>
            <el-option label="简单" value="easy"></el-option>
            <el-option label="中等" value="medium"></el-option>
            <el-option label="困难" value="hard"></el-option>
          </el-select>
        </div>

        <div class="filter-group">
          <h3>题目类型</h3>
          <el-select
              v-model="filterType"
              placeholder="选择题目类型"
              size="large"
              style="width: 100%"
              clearable
          >
            <el-option label="全部类型" value="all"></el-option>
            <el-option label="选择题" value="choice"></el-option>
            <el-option label="填空题" value="fill_in"></el-option>
          </el-select>
        </div>
      </div>

      <!-- 题目列表 -->
      <div class="questions-container">
        <div v-if="loading" style="text-align: center; padding: 40px;">
          <i class="fas fa-spinner fa-spin" style="font-size: 24px;"></i>
          <p>加载中...</p>
        </div>

        <div v-else-if="filteredQuestions.length === 0" class="empty-state">
          <i class="fas fa-book-open"></i>
          <h3>暂无收藏题目</h3>
          <p>您还没有收藏任何题目，快去题库看看吧</p>
        </div>

        <template v-else>
          <div v-for="(question, index) in paginatedQuestions" :key="index" class="question-card">
            <div class="question-header">
              <div class="question-type" :class="{
                'type-choice': question.questionType === 'choice',
                'type-fill': question.questionType !== 'choice'
              }">
                {{ question.questionType === 'choice' ? '选择题' : '填空题' }}
              </div>
              <div class="difficulty">
                <el-tag v-if="question.weight < 1" type="success" size="small">简单</el-tag>
                <el-tag v-if="question.weight >= 1 && question.weight < 1.3" type="warning" size="small">中等</el-tag>
                <el-tag v-if="question.weight >= 1.3" type="danger" size="small">困难</el-tag>
              </div>
            </div>

            <div class="question-content">
              <p>{{ question.content }}</p>

              <!-- 选择题选项 -->
              <div v-if="question.questionType === 'choice'" class="choices" style="margin-top: 15px;">
                <div v-for="(choice, cIndex) in question.choices" :key="cIndex"
                     :style="{
                       margin: '8px 0',
                       padding: '8px 12px',
                       borderRadius: '6px',
                       background: choice.isCorrect ? '#f0f9eb' : '#f8f9fa',
                       border: choice.isCorrect ? '1px solid #67c23a' : 'none'
                     }">
                  {{ choice.choiceContent }}
                  <span v-if="choice.isCorrect" style="color: #67c23a; margin-left: 8px;">
                    <i class="fas fa-check"></i> 正确答案
                  </span>
                </div>
              </div>

              <!-- 填空题答案 -->
              <div v-if="question.questionType !== 'choice'"
                   style="margin-top: 15px; background: #f0f9eb; padding: 10px; border-radius: 6px;">
                <p><strong>正确答案：</strong> {{ question.answer }}</p>
              </div>
            </div>

            <div class="question-footer">
              <div class="question-info">
                <span><i class="fas fa-layer-group"></i> {{ question.categoryName }}</span>
                <span><i class="fas fa-graduation-cap"></i> {{ question.majorName }}</span>
                <span><i class="fas fa-calendar"></i> {{ formatDate(question.createdAt) }}</span>
              </div>

              <div class="favorite-btn" @click="toggleFavorite(question)">
                <svg
                      :fill="question.isFavorited ? '#ffb600' : '#ccc'"
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                  >
                    <path d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 
                    1.416 8.279-7.432-3.907-7.432 3.907 1.416-8.279-6.064-5.828 
                    8.332-1.151z" 
                    stroke="none" 
                    stroke-width="0" 
                    fill-rule="evenodd"
                    transform="scale(0.9) translate(1.2, 1)"
                  />
                </svg>
              </div>
            </div>
          </div>

          <!-- 分页控件 -->
          <div class="pagination-container">
            <el-pagination
                background
                layout="prev, pager, next"
                :total="filteredQuestions.length"
                :page-size="pageSize"
                :current-page="currentPage"
                @current-change="currentPage = $event"
                hide-on-single-page
            />
          </div>
        </template>
      </div>

      <!-- 题目练习对话框 -->
      <el-dialog
          v-model="dialogVisible"
          title="收藏题目练习"
          width="800px"
          :close-on-click-modal="false"
          :before-close="handleDialogClose"
          custom-class="custom-dialog"
      >
        <div v-if="currentQuestion" class="question-block">
          <div class="question-header">
            <div class="question-number">第 {{ currentQuestionIndex + 1 }} 题 (共 {{ questions.length }} 题)</div>
            <div class="question-type">
              {{ currentQuestion.questionType === 'choice' ? '选择题' : '填空题' }}
            </div>
          </div>

          <div class="question-content">
            {{ currentQuestion.content }}
          </div>

          <!-- 选择题 -->
          <div class="options-container" v-if="currentQuestion.questionType === 'choice'">
            <el-radio-group v-model="selectedAnswer" class="radio-options-group">
              <el-radio
                  v-for="(option, index) in currentQuestion.choices"
                  :key="index"
                  :label="option.choiceContent"
              >
                {{ option.choiceContent }}
                <span v-if="option.isCorrect && showCorrectAnswer" style="color: #67c23a; margin-left: 8px;">
                  <i class="fas fa-check"></i> 正确答案
                </span>
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 填空题 -->
          <div class="fill_in-container" v-if="currentQuestion.questionType !== 'choice'">
            <el-input
                v-model="selectedAnswer"
                placeholder="请输入答案"
                clearable
            />
            <div v-if="showCorrectAnswer" class="correct-answer" style="margin-top: 10px;">
              <i class="fas fa-check-circle"></i> 正确答案：<strong>{{ currentQuestion.answer }}</strong>
            </div>
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <div class="action-buttons-full">
              <div class="left-buttons">
                <el-button
                    link
                    class="favorite-btn"
                    @click="toggleFavorite(currentQuestion)"
                    title="收藏/取消收藏"
                >
                  <svg
                      :fill="currentQuestion.isFavorited ? '#ffb600' : '#ccc'"
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                  >
                    <path d="M12 .587l3.668 7.568 8.332 1.151-6.064 5.828 
                    1.416 8.279-7.432-3.907-7.432 3.907 1.416-8.279-6.064-5.828 
                    8.332-1.151z" 
                    stroke="none" 
                    stroke-width="0" 
                    fill-rule="evenodd"
                    transform="scale(0.9) translate(1.2, 1)"
                  />
                </svg>
                </el-button>

                <el-button @click="prevQuestion" :disabled="currentQuestionIndex === 0">
                  <i class="fas fa-arrow-left"></i> 上一题
                </el-button>
                <el-button @click="nextQuestion" :disabled="currentQuestionIndex >= questions.length - 1">
                  下一题 <i class="fas fa-arrow-right"></i>
                </el-button>
              </div>

              <div class="right-buttons">
                <el-button @click="dialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="submitAnswer">提交答案</el-button>
              </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-section">
              <h3><i class="fas fa-comments"></i> 题目评论</h3>

              <!-- 评论列表滚动区域 -->
              <div class="comment-list-wrapper">
                <div v-if="comments && comments.length > 0" class="comments-list">
                  <div
                      v-for="(comment, idx) in comments"
                      :key="idx"
                      class="comment-item"
                  >
                    <div class="comment-author">
                      <i class="fas fa-user-circle"></i> {{ comment.author }}
                    </div>
                    <div class="comment-content">
                      {{ comment.content }}
                    </div>
                    <div class="comment-like">
                      <el-button
                          link
                          class="like-btn"
                          @click="toggleLike(comment)"
                          title="点赞 / 取消点赞"
                      >
                        <svg
                            width="20"
                            height="20"
                            viewBox="0 0 24 24"
                            :fill="comment.hasLiked ? '#f56c6c' : '#ccc'"
                        >
                          <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5
               2 6.01 4.01 4 6.5 4c1.74 0 3.41 1.01 4.13 2.44h1.74C14.09 5.01 15.76 4 17.5 4
               19.99 4 22 6.01 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                        </svg>
                        <span style="margin-left: 4px">{{ comment.likeCount }}</span>
                      </el-button>

                      <!-- 删除按钮（当前用户是作者或管理员才显示） -->
                      <el-button
                          v-if="comment.userId === currentUserId || isAdmin"
                          link
                          class="delete-btn"
                          @click.stop="deleteComment(comment.commentId)"
                          title="删除评论"
                      >
                        <svg
                            width="20"
                            height="20"
                            viewBox="0 0 24 24"
                            fill="#f56c6c"
                        >
                          <path d="M3 6h18v2H3V6zm2 3h14v13H5V9zm3 3v7h2v-7H8zm4 0v7h2v-7h-2zm4 0v7h2v-7h-2z"/>
                        </svg>
                        <span style="margin-left: 4px">删除</span>
                      </el-button>
                    </div>
                  </div>
                </div>

                <div v-else class="no-comments">
                  <p>暂无评论，快来发表你的见解！</p>
                </div>
              </div>

              <!-- 输入框和按钮 -->
              <el-input
                  v-model="newComment"
                  placeholder="写下你的评论..."
                  type="textarea"
                  :rows="3"
                  class="new-comment-input"
              />
              <el-button
                  type="primary"
                  class="submit-comment-btn"
                  @click="submitComment"
              >
                <i class="fas fa-paper-plane"></i> 提交评论
              </el-button>
            </div>
          </div>
        </template>
      </el-dialog>
    </el-main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/useUserstore'
import axios from "@/api/server"

const router = useRouter()
const userStore = useUserStore()

// 收藏题目相关状态
const favorites = ref([])
const filterType = ref('all')
const filterMajor = ref('all')
const filterDifficulty = ref('all')
const loading = ref(false)
const majorOptions = ref([])
const currentPage = ref(1)
const pageSize = ref(3)

// 练习相关状态
const dialogVisible = ref(false)
const currentQuestionIndex = ref(0)
const selectedAnswer = ref('')
const currentQuestion = ref(null)
const showCorrectAnswer = ref(false)
const questions = ref([])
const comments = ref([])
const newComment = ref('')
const currentUserId = ref(null)
const isAdmin = ref(false)
const activeMenu = ref('3')

// 计算属性
const filteredQuestions = computed(() => {
  return favorites.value.filter(question => {
    if (filterType.value !== 'all' && question.questionType !== filterType.value) return false
    if (filterMajor.value !== 'all' && question.majorId.toString() !== filterMajor.value) return false

    if (filterDifficulty.value !== 'all') {
      if (filterDifficulty.value === 'easy' && question.weight >= 1) return false
      if (filterDifficulty.value === 'medium' && (question.weight < 1 || question.weight >= 1.3)) return false
      if (filterDifficulty.value === 'hard' && question.weight < 1.3) return false
    }

    return true
  })
})

const paginatedQuestions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredQuestions.value.slice(start, end)
})

const stats = computed(() => ({
  total: favorites.value.length,
  majors: [...new Set(favorites.value.map(q => q.majorName))].length,
  categories: [...new Set(favorites.value.map(q => q.categoryName))].length
}))

// 方法
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

const toggleFavorite = async (question) => {
  try {
    await axios.post(`/users/favorite/${question.questionId}`)

    if (dialogVisible.value) {
      // 在练习模式下，只更新当前问题的收藏状态
      question.isFavorited = !question.isFavorited
    } else {
      // 在列表模式下，从收藏列表中移除该题目
      favorites.value = favorites.value.filter(q => q.questionId !== question.questionId)
    }

    ElMessage.success(question.isFavorited ? '题目已收藏' : '已取消收藏')
  } catch (error) {
    console.error('操作收藏失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 开始练习收藏的题目
const startPractice = async () => {
  if (favorites.value.length === 0) {
    ElMessage.warning('您还没有收藏任何题目')
    return
  }

  try {
    questions.value = [...filteredQuestions.value]
    currentQuestionIndex.value = 0
    currentQuestion.value = questions.value[0]
    selectedAnswer.value = ''
    showCorrectAnswer.value = false
    dialogVisible.value = true

    // 加载第一题的评论
    await loadComments()
  } catch (error) {
    console.error('开始练习失败:', error)
    ElMessage.error('开始练习失败，请重试')
  }
}

// 提交答案
const submitAnswer = async () => {
  if (!selectedAnswer.value) {
    ElMessage.warning('请选择或填写答案')
    return
  }

  try {
    const question = currentQuestion.value
    const isCorrect = question.questionType === 'choice'
        ? question.choices.some(c => c.isCorrect && c.choiceContent === selectedAnswer.value)
        : question.answer === selectedAnswer.value

    // 更新用户答题记录
    await axios.post('/question/submit', {
      questionId: question.questionId,
      submitAnswer: selectedAnswer.value
    })

    showCorrectAnswer.value = true
    ElMessage[isCorrect ? 'success' : 'error'](isCorrect ? '回答正确!' : '回答错误')
  } catch (error) {
    console.error('提交答案失败:', error)
    ElMessage.error('提交答案失败，请重试')
  }
}

// 上一题
const prevQuestion = async () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    currentQuestion.value = questions.value[currentQuestionIndex.value]
    selectedAnswer.value = ''
    showCorrectAnswer.value = false
    await loadComments()
  }
}

// 下一题
const nextQuestion = async () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
    currentQuestion.value = questions.value[currentQuestionIndex.value]
    selectedAnswer.value = ''
    showCorrectAnswer.value = false
    await loadComments()
  } else {
    ElMessage.success('已经是最后一题了')
  }
}

// 加载评论
const loadComments = async () => {
  if (!currentQuestion.value) return

  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      currentUserId.value = userInfo.userId
      isAdmin.value = userInfo.isAdmin || false
    } catch {
      currentUserId.value = null
      isAdmin.value = false
    }
  }

  try {
    const res = await axios.get(`/users/comments/get/${currentQuestion.value.questionId}`)
    const commentList = res.data.data || []

    let likedCommentIds = []
    const token = localStorage.getItem('token')
    let likeCountList = []

    if (token) {
      const likeRes = await axios.get(`/users/commentlike/list/${currentQuestion.value.questionId}`, {
        headers: { Authorization: `Bearer ${token}` }
      })
      likedCommentIds = likeRes.data.data || []
    }

    if (token) {
      try {
        const likeCountRes = await axios.get(`/users/commentlike/count/${currentQuestion.value.questionId}`, {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
        likeCountList = likeCountRes.data.data || []
      } catch (e) {
        console.warn('获取点赞数量失败', e)
      }
    }

    // 设置每条评论的 hasLiked 和 likeCount
    for (const comment of commentList) {
      comment.hasLiked = likedCommentIds.includes(comment.commentId)
      comment.likeCount = likeCountList.find(item => item.commentId === comment.commentId)?.likeCount || 0
    }

    comments.value = commentList
  } catch {
    comments.value = []
  }
}

// 提交评论
const submitComment = async () => {
  const token = localStorage.getItem('token')
  const userInfoString = localStorage.getItem('userInfo')
  const userId = userInfoString ? JSON.parse(userInfoString)?.userId : null

  if (!token || !userId) {
    ElMessage.warning('请先登录后再评论')
    return
  }

  if (!newComment.value.trim()) {
    ElMessage.warning('评论不能为空')
    return
  }

  try {
    await axios.post('/users/comments/add', {
      questionId: currentQuestion.value.questionId,
      content: newComment.value.trim()
    })

    ElMessage.success('评论成功')
    newComment.value = ''
    await loadComments()
  } catch {
    ElMessage.error('评论失败')
  }
}

// 删除评论
const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm('确定要删除该评论吗？', '删除确认', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    await axios.delete(`/users/comments/delete/${commentId}`, {
      headers: { Authorization: `Bearer ${token}` }
    })

    ElMessage.success('评论删除成功')
    await loadComments()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('评论删除失败')
    }
  }
}

// 点赞/取消点赞评论
const toggleLike = async (comment) => {
  const token = localStorage.getItem('token')
  const userInfoString = localStorage.getItem('userInfo')
  const userId = userInfoString ? JSON.parse(userInfoString)?.userId : null

  if (!token || !userId) {
    ElMessage.warning('请先登录后再点赞')
    return
  }

  try {
    await axios.post(`/users/commentlike/${comment.commentId}`, null, {
      headers: { Authorization: `Bearer ${token}` }
    })

    comment.hasLiked = !comment.hasLiked
    comment.likeCount += comment.hasLiked ? 1 : -1
    ElMessage.success(comment.hasLiked ? '点赞成功' : '取消点赞成功')
  } catch {
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 关闭对话框
const handleDialogClose = (done) => {
  ElMessageBox.confirm('确定要结束练习吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    done()
  }).catch(() => {})
}

// 获取收藏题目
const fetchFavorites = async () => {
  loading.value = true
  try {
    const userId = userStore.userInfo.userId
    if (!userId) {
      ElMessage.error('用户信息获取失败')
      return
    }

    const response = await axios.get('/users/favorite/get', {
      params: { userId }
    })

    if (response.data.code === 1 && response.data.data) {
      favorites.value = response.data.data.map(item => {
        // 处理选择题选项 - 去除重复选项
        const uniqueChoices = []
        const seenChoices = new Set()

        if (item.questionChoicesList) {
          item.questionChoicesList.forEach(choice => {
            const key = `${choice.choiceContent}-${choice.isCorrect}`
            if (!seenChoices.has(key)) {
              seenChoices.add(key)
              uniqueChoices.push(choice)
            }
          })
        }

        return {
          questionId: item.questionId,
          questionType: item.questionType,
          content: item.content,
          answer: item.answer,
          choices: uniqueChoices,
          baseScore: item.baseScore,
          weight: item.weight || 1.0,
          createdAt: item.createdAt,
          createdBy: item.createdBy,
          majorId: item.majorId,
          majorName: item.majorName,
          categoryId: item.categoryId,
          categoryName: item.categoryName,
          isFavorited: true
        }
      })
    } else {
      ElMessage.error('获取收藏列表失败: ' + (response.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取专业列表
const fetchMajorList = async () => {
  try {
    const response = await axios.get('/admin/manage/majors')
    if (response.data.code === 1 && response.data.data) {
      majorOptions.value = response.data.data.map(item => ({
        value: item.majorId.toString(),
        label: item.majorName
      }))
    } else {
      ElMessage.error('获取专业列表失败：' + (response.data.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取专业列表失败', error)
    ElMessage.error('获取专业列表失败，请稍后重试')
  }
}

// 导航相关方法
const handleSelect = (index) => {
  activeMenu.value = index
}

const goBackHome = () => {
  router.push('/home')
}

const goToPersonal = () => {
  router.push('/personal')
}

const goToCollection = () => {
  router.push('/collection')
}

const goToLogin = () => {
  localStorage.removeItem('token')
  router.push('/')
}

// 当过滤条件变化时重置页码
watch([filterType, filterMajor, filterDifficulty], () => {
  currentPage.value = 1
})

onMounted(() => {
  fetchFavorites()
  fetchMajorList()
})
</script>


<style scoped>
@import "../styles/Collection.css";
</style>
